<template>
  <view id="page">
    <view class="action">
      <view :class="[disabled ? 'hidden' : '']" class="action-cancel" @click="onCancel">取消</view>
      <view class="action-confirm bg-primary" @click="disabled ? onEdit() : onSave()">
        {{ disabled ? '编辑' : '保存' }}
      </view>
    </view>
    <view>
      <view class="item flex-row">
        <view class="">头像</view>
        <avatar v-if="disabled" :avatar="userInfo.avatar" hover-class="none"></avatar>
        <van-uploader
          v-if="!disabled"
          :file-list="fileList"
          max-count="1" :deletable="true"
          @afterRead="afterRead"
          @delete="deleteImg"
        />
      </view>
      <view class="item flex-row">
        <view class="item-label" style="color: #363636;">用户名</view>
        <input style="color:#afafaf;"
               v-model="userInfo.userName"
               disabled
               class="item-value"
        />
      </view>
      <view class="item flex-row">
        <view class="item-label" :style="{'color':disabled ? '#363636' : '#afafaf'}">昵称</view>
        <input :style="{'color':disabled ? '#afafaf' : '#363636'}"
               v-model="userInfo.nickName"
               :disabled="disabled"
               class="item-value"
        />
      </view>
      <view class="item flex-row">
        <view class="item-label" :style="{'color':disabled ? '#363636' : '#afafaf'}">手机号</view>
        <input type="number" maxlength="11" :style="{'color':disabled ? '#afafaf' : '#363636'}"
               v-model="userInfo.phonenumber"
               :disabled="disabled"
               class="item-value"
        />
      </view>
      <view class="item flex-row">
        <view class="item-label" :style="{'color':disabled ? '#363636' : '#afafaf'}">邮箱</view>
        <input type="email" :style="{'color':disabled ? '#afafaf' : '#363636'}"
               v-model="userInfo.email"
               :disabled="disabled"
               class="item-value"
        />
      </view>
      <view class="item flex-row">
        <view class="item-label" :style="{'color':disabled ? '#363636' : '#afafaf'}">性别</view>
        <view v-if="disabled">
          <text v-if="userInfo.sex=='0'" style="color: #afafaf;" class="item-value">男</text>
          <text v-else-if="userInfo.sex=='1'" style="color: #afafaf;" class="item-value">女</text>
          <text v-else style="color: #afafaf;" class="item-value">未知</text>
        </view>
        <!--        <input style="color: #afafaf;"
                       v-model=""
                       disabled
                       class="item-value"
                />-->
        <van-radio-group v-if="!disabled"
                         :value="sex"
                         @change="onChange"
                         direction="horizontal"
        >
          <van-radio name="0">男</van-radio>
          <van-radio name="1">女</van-radio>
        </van-radio-group>
      </view>
    </view>
  </view>
</template>

<script>
import {getToken} from "../../../../utils/auth";
import {updateUserProfile, uploadAvatar, uploadCommon} from "../../../../api/user";
import Bus from "../../../../utils/bus";

export default {
  name: "userInfo",
  data() {
    return {
      fileList: [],
      disabled: true,
      userInfo: {},
      postGroup: {},
      sex: ''
    }
  },
  computed: {},
  mounted() {
    this.userInfo = JSON.parse(this.$root.$mp.query.userInfo);
    this.userInfo.avatar = this.changeUrl(this.userInfo.avatar)
    this.fileList = JSON.parse(this.$root.$mp.query.fileList);
    this.sex = this.userInfo.sex;
    /*this.fileList.url='http://42.192.211.158:8888/zutassociation'+this.userInfo.avatar
    this.fileList.name='头像'*/
    this.postGroup = JSON.parse(this.$root.$mp.query.postGroup);
  },
  methods: {
    deleteImg(val) {
      this.fileList = []
    },
    async afterRead(event) {
      const {file} = event.mp.detail
      var _this = this;
      // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
      await wx.showToast({
        icon: "loading",
        title: "正在上传"
      })
      wx.uploadFile({
        url: 'http://42.192.211.158:8888/zutassociation/common/upload', // 仅为示例，非真实的接口地址
        filePath: file.url,
        name: 'file',
        headers: {Authorization: "Bearer " + getToken()},
        // formData: {
        //   //和服务器约定的token, 一般也可以放在header中
        //   'session_token': wx.getStorageSync('session_token')
        // },
        success(res) {
          let data = JSON.parse(res.data)
          if (data.code !== 200) {
            this.setModal({content: '图片上传失败'})
            return;
          }
          let currentFile = {fileName: data.fileName, url: data.url};
          let list = []
          list.push(currentFile)
          _this.fileList=list
        },
        fail: function (e) {
          console.log(e);
          this.setModal({content: '图片上传失败'})
        },
        complete: function () {
          wx.hideToast();  //隐藏Toast
          // this.fileList = wx.getStorageSync('list')
        }
      });
    },
    onChange(event) {
      this.sex = event.mp.detail
    },

    onEdit() {
      this.disabled = false
    },

    onSave() {
      if (!this.userInfo.nickName) {
        this.setToast({title: "昵称不能为空"});
        return
      } else if (this.userInfo.nickName.length < 1 || this.userInfo.nickName.length > 20) {
        this.setToast({title: "昵称长度应在1-20个字符之间"});
        return
      } else if (!this.userInfo.phonenumber) {
        this.setToast({title: "手机号码不能为空"});
        return
      } else if (!(/^1[3|4|5|6|7|8|9][0-9]\d{8}$/.test(this.userInfo.phonenumber)) || this.userInfo.phonenumber.length != 11) {
        this.setToast({title: "请输入11位有效的手机号码"});
        return;
      } else if (this.userInfo.email) {
        if (!(/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(this.userInfo.email))) {
          this.setToast({title: "请输入正确的邮箱地址"});
          return
        }
      }
      this.userInfo.sex = this.sex
      this.userInfo.avatar = this.fileList[0].fileName
      let data = JSON.parse((JSON.stringify(this.userInfo)))
      updateUserProfile(data).then(response => {
        if (response.code === 200) {
          this.userInfo.avatar = this.changeUrl(this.userInfo.avatar)
          Bus.$emit('跳转刷新', 'onSave');
          this.setToast({title: "保存成功"});
        } else {
          this.setToast({title: response.msg});
        }
      });
      this.disabled = true
    },

    onCancel() {
      this.userInfo = JSON.parse(this.$root.$mp.query.userInfo);
      this.userInfo.avatar = this.changeUrl(this.userInfo.avatar)
      this.fileList = JSON.parse(this.$root.$mp.query.fileList);
      this.disabled = true
      this.sex = this.userInfo.sex
    }
  }
}
</script>

<style scoped>
.action {
  display: flex;
  justify-content: space-between;
  padding: 15px;
}

.action-cancel,
.action-confirm {
  padding: 5px 10px;
  border-radius: 5px;
}

.action-cancel {
  background-color: #f0f0f0;
}

.item {
  align-items: center;
  justify-content: space-between;
  background-color: white;
  border-bottom: 1px solid #eeeeee;
  padding: 15px;
}

.item-value {
  text-align: right;
}

.hidden {
  visibility: hidden;
}
</style>
